package com.gcloud.controller.compute.service.vm.senior.impl;

import com.gcloud.controller.compute.dao.InstanceDao;
import com.gcloud.controller.compute.dao.InstanceTypeDao;
import com.gcloud.controller.compute.entity.InstanceType;
import com.gcloud.controller.compute.entity.VmInstance;
import com.gcloud.controller.compute.service.vm.senior.IVmSeniorService;
import com.gcloud.core.exception.GCloudException;
import com.gcloud.header.compute.enums.VmState;
import com.gcloud.header.compute.enums.VmTaskState;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by yaowj on 2018/12/3.
 */
@Service
@Slf4j
public class VmSeniorServiceImpl implements IVmSeniorService {

    @Autowired
    private InstanceDao instanceDao;

    @Autowired
    private InstanceTypeDao instanceTypeDao;

    @Override
    public void bundle(String instanceId, boolean inTask) {

        VmInstance vm = instanceDao.getById(instanceId);
        if (vm == null) {
            throw new GCloudException("0011202::云服务器不能存在");
        }

        if(!inTask){
            if (!instanceDao.updateInstanceTaskState(instanceId, VmTaskState.BUNDLING)) {
                throw new GCloudException("0011203::云服务器当前状态不能创建镜像");
            }
        }

    }

    @Override
    public void modifyInstanceInit(String instanceId, String instanceType, boolean inTask) {
        VmInstance instance = instanceDao.getById(instanceId);
        if (instance == null) {
            throw new GCloudException("0011303::云服务器不存在");
        }

        InstanceType insType = instanceTypeDao.getById(instanceType);
        if (insType == null) {
            throw new GCloudException("0011304::实例类型不存在");
        }

        //关机才能修改配置，功能更加稳定，否则如果虚拟机无法通过libvirt命令关机，则会超时
        //关机才能配置，所以不需要处理资源
        if(!VmState.STOPPED.value().equals(instance.getState())){
            throw new GCloudException("0011305::请先关闭云服务器");
        }

        if(!inTask){
            if (!instanceDao.updateInstanceTaskState(instanceId, VmTaskState.MODIFYING_CONFIG)) {
                throw new GCloudException("0011306::云服务器当前状态不能修改实例规格");
            }
        }
    }
}
